﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web.UI.WebControls;
using DataAccess;
using SubSonic;
using System.Data;
using System.Data.SqlClient;

namespace Business
{
    public struct contractCollection
    {
        static contractCollection()
        {
            
        }
    }
    public static class CommonCalculations
    {

        public static bool HasDelayCalculator(Guid contractId)
        {
            TblTaskCollection taskCollection = new TblTaskCollection();
            taskCollection.LoadAndCloseReader(DataAccess.TblTask.FetchByParameter(TblTask.Columns.ContractId, Comparison.Equals, contractId));
            foreach (var VARIABLE in taskCollection)
            {
                if (Convert.ToInt32(VARIABLE.DelayDays) >= 0)
                    return true;
            }
            return false;
        }

        public static int DelayCalculator(Guid contractId)
        {
            TblTaskCollection taskCollection = new TblTaskCollection();

            taskCollection.LoadAndCloseReader(DataAccess.TblTask.FetchByParameter(TblTask.Columns.ContractId, Comparison.Equals, contractId));
            int delay = 0;
            foreach (var task in taskCollection)
            {
                delay += Convert.ToInt32(task.DelayDays);
            }
            return delay;
        }

        public static int DelayCalculator(TblTaskCollection taskCollection)
        {
            int delay = 0;
            foreach (var task in taskCollection)
            {
                delay += Convert.ToInt32(task.DelayDays);
            }
            return delay;
        }


        public static int ProgressCalculator(Guid contractId)
        {
            TblTaskCollection taskCollection = new TblTaskCollection();
            TblStepsAdvisorCollection advisorCollection = new TblStepsAdvisorCollection();
            TblStepsSurveyorCollection surveyorCollection = new TblStepsSurveyorCollection();
            int steps = 0;
            int progress = 0;
            taskCollection.LoadAndCloseReader(TblTask.FetchByParameter(TblTask.Columns.ContractId, Comparison.Equals, contractId));
            if (taskCollection.Count > 0 && taskCollection[0].AdvisorStepId != null)
            {
                //SqlConnection con = new SqlConnection(DataAccess.Global.GetConnectionString().ToString());
                //con.Open();
                //SqlCommand com = new SqlCommand("select Name from TblStepsAdvisor", con);
                //SqlDataReader dr = com.ExecuteReader();
               
                
                //while (dr.Read())
                //    steps += 1;
                //dr.Close(); 
                //con.Close();
                ////advisorCollection.LoadAndCloseReader(TblStepsAdvisor.FetchAll());
                steps = 18;
            }
            else
            {
                surveyorCollection.LoadAndCloseReader(TblStepsSurveyor.FetchAll());
                steps = surveyorCollection.Count;
            }
            Query q = new Query(TblTask.Schema);
            q.AddWhere(TblTask.Columns.ContractId, Comparison.Equals, contractId);
            q.AddWhere(TblTask.Columns.AdvisorStepId, Comparison.IsNot, null);
            q.AddWhere(TblTask.Columns.IsDonei, Comparison.Equals, true);
            q.DISTINCT();
            taskCollection.LoadAndCloseReader(q.ExecuteReader());
            progress = (taskCollection.Count /steps )*100;
            return progress;
        }

        public static string ContractTypeNameString(TblContract contract)
        {
            if (Convert.ToBoolean(contract.ContractType))
            {
                return "مشاوره";
            }
            else
            {
                return "نقشه برداری";
            }
        }

        public static string ContractTypeNameString(Guid contractId)
        {
            TblContract contract = TblContract.FetchByID(contractId);

            if (Convert.ToBoolean(contract.ContractType))
            {
                return "مشاوره";
            }
            else
            {
                return "نقشه برداری";
            }
        }

        public static string ContractTypeNameString(Boolean contractType)
        {
            if (contractType)
            {
                return "مشاوره";
            }
            else
            {
                return "نقشه برداری";
            }
        }


        public static bool ContractType(TblContract contract)
        {
            if (Convert.ToBoolean(contract.ContractType))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public static bool ContractType(Guid contractId)
        {
            TblContract contract = TblContract.FetchByID(contractId);

            if (Convert.ToBoolean(contract.ContractType))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static string FindDoerOfProject(Guid contractId)
        {
            try
            {
                Guid userId = TblContract.FetchByID(contractId).UserId;
                string Name = "";

                IDataReader dr = DataAccess.TblUserDetail.FetchByParameter("UserId", userId);
                if (dr.Read())
                {
                  if(dr["Name"].ToString()!="")
                  {
                    if (dr["Role"].ToString() == "Advisorhoghooghi")
                    {
                       Name = dr["Name"].ToString();
                    }
                   else
                    {
                       Name = dr["Name"].ToString()+" " + dr["Family"].ToString();
                    }  
                  }
                
                  else
                  {
                   return "نام فرد ثبت نشده";
                  }
                    dr.Close();
                }
                return Name;
                  
                }
              
          
            catch (Exception ex)
            {
                return "مشخص نشده";
            }
        }

        public static string FindFourthFactorByContractId(Guid contractId)
        {
            try
            {
                Guid fourthFactorId = new Guid(TblContract.FetchByID(contractId).FourthFactorUserId.ToString());
                string Name = "";

                IDataReader dr = DataAccess.TblUserDetail.FetchByParameter("UserId", fourthFactorId);
                if (dr.Read())
                {
                    if (dr["Name"].ToString() != "")
                    {
                        if (dr["Role"].ToString() == "Advisorhoghooghi")
                        {
                            Name = dr["Name"].ToString();
                        }
                        else
                        {
                            Name = dr["Name"].ToString() + " " + dr["Family"].ToString();
                        }
                    }

                    else
                    {
                        return "نام فرد ثبت نشده";
                    }
                    dr.Close();
                }
                return Name;
            }
            catch (Exception ex)
            {
                return "مشخص نشده";
            }
        }

        public static string VillageNameByContractId(Guid contractId)
        {
            try
            {
                TblContract contract = new TblContract();
                TblVillage village = new TblVillage();
                contract = TblContract.FetchByID(contractId);
                village = TblVillage.FetchByID(contract.VillageId);
                return village.Name;
            }
            catch (Exception ex)
            {
                return "اطلاعات روستا وجود ندارد";
            }
        }

        public static string CityNameByContractId(Guid contractId)
        {
            try
            {
                TblContract contract = new TblContract();
                TblVillage village = new TblVillage();
                TblDehestan dehestan = new TblDehestan();
                contract = TblContract.FetchByID(contractId);
                village = TblVillage.FetchByID(contract.VillageId);
                dehestan = TblDehestan.FetchByID(village.DehstanId);
                return dehestan.Name;
            }
            catch (Exception ex)
            {
                return "اطلاعات شهرستان وجود ندارد";
            }
        }

        public static int SortSteps(ProjectStatusTaskType i, ProjectStatusTaskType j)
        {
            if (i.StepPriority > j.StepPriority)
            {
                return 1;
            }
            if (i.StepPriority < j.StepPriority)
            {
                return -1;
            }
            if (i.StepPriority == j.StepPriority)
            {
                return 0;
            }
            return 0;
        }

        public static int StepsCount(Guid contractId)
        {
            TblContract contract = TblContract.FetchByID(contractId);

            if (Convert.ToBoolean(contract.ContractType))
            {
                TblStepsAdvisorCollection stepsAdvisorCollection = new TblStepsAdvisorCollection();
                stepsAdvisorCollection.LoadAndCloseReader(TblStepsAdvisor.FetchAll(OrderBy.Asc(TblStepsAdvisor.Columns.Priority)));
                return stepsAdvisorCollection.Count;
            }
            else
            {
                TblStepsSurveyorCollection stepsSurveyorCollection = new TblStepsSurveyorCollection();
                stepsSurveyorCollection.LoadAndCloseReader(TblStepsSurveyor.FetchAll(OrderBy.Asc(TblStepsSurveyor.Columns.Priority)));
                return stepsSurveyorCollection.Count;
            }
        }



        public static int CountEnteredTasks(Guid contractId)
        {
            TblTaskCollection taskCollection = new TblTaskCollection();
            taskCollection.LoadAndCloseReader(TblTask.FetchByParameter(TblTask.Columns.ContractId, Comparison.Equals, contractId));
            return taskCollection.Count;
        }

        public static List<string> GetAllSteps(Guid contractId)
        {
            List<string> output = new List<string>();
            if (Convert.ToBoolean(TblContract.FetchByID(contractId).ContractType))
            {
                TblStepsAdvisorCollection ret = new TblStepsAdvisorCollection();
                ret.LoadAndCloseReader(TblStepsAdvisor.FetchAll(OrderBy.Asc(TblStepsAdvisor.Columns.Priority)));
                ret.OrderBy(steps => steps.Priority);
                foreach (var r in ret)
                {
                    r.Name = r.Priority + ". " + r.Name;
                    output.Add(r.Name);
                }
            }
            else
            {
                TblStepsSurveyorCollection ret = new TblStepsSurveyorCollection();
                ret.LoadAndCloseReader(TblStepsSurveyor.FetchAll(OrderBy.Asc(TblStepsSurveyor.Columns.Priority)));
                foreach (var r in ret)
                {
                    r.Name = r.Priority + ". " + r.Name;
                    output.Add(r.Name);
                }
            }
            return output;
        }

        public static int MaxHeightGridHeader(object gridViewInput)
        {
            GridView gridView = gridViewInput as GridView;
            int max = 0;
            foreach (var column in gridView.Columns)
            {
                TemplateField templateField = column as TemplateField;

                if (Convert.ToInt32(templateField.HeaderStyle.Height.Value) > max)
                    max = Convert.ToInt32((templateField.HeaderStyle.Height.Value));
            }
            return max + 1;
        }

        /// <summary>
        /// Makes an empty list of fields for inserting between items
        /// </summary>
        /// <param name="isAdvisor"></param>
        /// <returns></returns>
        public static List<ProjectStatusTaskType> EmptyListOfSteps(bool isAdvisor)
        {
            ProjectStatusTaskType projectStatusTaskType = new ProjectStatusTaskType();
            List<ProjectStatusTaskType> output = new List<ProjectStatusTaskType>();
            TblStepsAdvisorCollection advisorCollection = new TblStepsAdvisorCollection();
            advisorCollection.LoadAndCloseReader(TblStepsAdvisor.FetchAll());
            if (isAdvisor)
            {

                foreach (var step in advisorCollection)
                {
                    projectStatusTaskType.AdvisorStepId = step.Id;
                    projectStatusTaskType.StepName = step.Priority.ToString() + ". " + step.Name;
                    projectStatusTaskType.StepPriority = Convert.ToInt32(step.Priority);
                    projectStatusTaskType.HasRepeat = Convert.ToBoolean(step.HasRepeat);
                    output.Add(projectStatusTaskType);
                }
            }
            else
            {
                foreach (var step in advisorCollection)
                {
                    projectStatusTaskType.SurveyorStepId = step.Id;
                    projectStatusTaskType.StepName = step.Priority.ToString() + ". " + step.Name;
                    projectStatusTaskType.StepPriority = Convert.ToInt32(step.Priority);
                    projectStatusTaskType.HasRepeat = Convert.ToBoolean(step.HasRepeat);
                    output.Add(projectStatusTaskType);
                }
            }
            return output;
        }


        public static List<ProjectStatusTaskType> EmptyListOfSteps(Guid contractId)
        {

            List<ProjectStatusTaskType> output = new List<ProjectStatusTaskType>();
            TblStepsAdvisorCollection advisorCollection = new TblStepsAdvisorCollection();
            bool isAdvisor = Convert.ToBoolean(TblContract.FetchByID(contractId).ContractType);
            advisorCollection.LoadAndCloseReader(TblStepsAdvisor.FetchAll());
            if (isAdvisor)
            {

                foreach (var step in advisorCollection)
                {
                    ProjectStatusTaskType projectStatusTaskType = new ProjectStatusTaskType();
                    projectStatusTaskType.AdvisorStepId = step.Id;
                    projectStatusTaskType.StepName = step.Priority.ToString() + ". " + step.Name;
                    projectStatusTaskType.DateDoneFarsi = "";
                    projectStatusTaskType.StepPriority = Convert.ToInt32(step.Priority);
                    projectStatusTaskType.HasRepeat = Convert.ToBoolean(step.HasRepeat);
                    output.Add(projectStatusTaskType);
                }
            }
            else
            {
                foreach (var step in advisorCollection)
                {
                    ProjectStatusTaskType projectStatusTaskType = new ProjectStatusTaskType();
                    projectStatusTaskType.SurveyorStepId = step.Id;
                    projectStatusTaskType.StepName = step.Priority.ToString() + ". " + step.Name;
                    projectStatusTaskType.DateDoneFarsi = "";
                    projectStatusTaskType.StepPriority = Convert.ToInt32(step.Priority);
                    projectStatusTaskType.HasRepeat = Convert.ToBoolean(step.HasRepeat);
                    output.Add(projectStatusTaskType);
                }
            }
            return output;
        }

        public static List<TblContract> SelectProjectsByCity(Guid cityId)
        {
            List<TblContract> output = new List<TblContract>();
            TblBakhshCollection bakhshCollection = new TblBakhshCollection();
            TblDehestanCollection dehestanCollection = new TblDehestanCollection();
            TblVillageCollection villageCollection = new TblVillageCollection();
            TblContractCollection contractCollection = new TblContractCollection();
            bakhshCollection.LoadAndCloseReader(TblBakhsh.FetchByParameter(TblBakhsh.Columns.CityId, Comparison.Equals,
                                                                           cityId));
            foreach (var baksh in bakhshCollection)
            {
                dehestanCollection.LoadAndCloseReader(TblDehestan.FetchByParameter(TblDehestan.Columns.BakhshId,
                                                                                   Comparison.Equals, baksh.Id));
                foreach (var dehestan in dehestanCollection)
                {
                    villageCollection.LoadAndCloseReader(TblVillage.FetchByParameter(TblVillage.Columns.DehstanId,
                                                                                     Comparison.Equals, dehestan.Id));
                    foreach (var village in villageCollection)
                    {
                        contractCollection.LoadAndCloseReader(TblContract.FetchByParameter(
                            TblContract.Columns.VillageId, Comparison.Equals,
                            village.Id));
                    }
                    villageCollection.Clear();

                }
                dehestanCollection.Clear();
            }
            foreach (var contract in contractCollection)
            {
                output.Add(contract);
            }
            return output;
        }

        public static List<TblContract> SelectProjectsByYear(int year)
        {
            TblContractCollection contractCollection = new TblContractCollection();
            contractCollection.LoadAndCloseReader(TblContract.FetchByParameter(TblContract.Columns.Year, Comparison.Equals, year));
            return contractCollection.ToList();
        }

        public static List<TblContract> SelectProjectsByCityAndYear(Guid cityId, int year)
        {
            List<TblContract>  output = SelectProjectsByCity(cityId);
            foreach(var contract in output)
            {
                if (contract.Year != year)
                    output.Remove(contract);
            }
            return output;
        }
        
    }
}

